<?php
/**
 * Created by PhpStorm.
 * User:夏浩文
 * Date: 2017-06-20
 * Time: 上午 11:37
 */
namespace app\hongyanche\model;
use Composer\Package\Package;
use think\Db;
use think\paginator;
class forum {
    private $userId;
    private $auth;
    private $admin;
    private $config;
    function __construct()
    {
        //检查权限
        $this->admin = model('admin');
        $auth = $this->admin -> is('maintain');
        if($auth['state']){
            $this->auth = $auth['state'];
        }
        //获取user_id
        if (is_null($this->userId)) {
            $user_id = model('user');
            $userId = $this->userId = $user_id->getUserId();
        } else {
            $userId = $this->userId;
        }
        if (!$userId) {
            return;
        }
    }

    //--------------------------积分管理------------------------------
    //创建积分规则
    public function addRule($data)
    {
        if(!$data['way']) return ['state'=>0,'errormsg'=>'请选择获得积分的方式'];
        if(!$data['amount']) return ['state'=>0,'errormsg'=>'请输入积分数量'];
        $data['state'] = 1;
        $data['create_time'] = time();
        $data['user_id'] = $this->userId;
        $res = db('forum_points_rule')->insert($data);
        if(!$res) return ['state'=>0,'errormsg'=>'设置失败'];
        return ['state'=>1,'errormsg'=>'成功'];
    }
    public function rule_modify($id,$key,$content){
        if($key == 'upper_limit') {
            $res = db('forum_points_rule')->where("state = 1")->update([$key=>$content]);
            if(!$res) return ['state'=>0,'errormsg'=>'修改失败'];
            return ['state'=>1,'errormsg'=>'成功'];
        }
        if(!$id) return ['state'=>0,'errormsg'=>'参数错误'];
        $data['state'] = 1;
        $data['create_time'] = time();
        $data['user_id'] = $this->userId;
        $data[$key] = $content;
        $res = db('forum_points_rule')->where("rule_id = $id")->update($data);
        if(!$res) return ['state'=>0,'errormsg'=>'设置失败'];
        return ['state'=>1,'errormsg'=>'成功'];
    }
    public function rule_list()
    {
        $res = db('forum_points_rule')->where("state = 1")->cache(true,86400)->select();
        if(!$res) return ['state'=>1,'data'=>[]];
        return ['state'=>1,'data'=>['list'=>$res]];
    }

    //--------------------------板块管理------------------------------
    //创建板块名
    public function label_add($cn)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if(!model('admin')->is('forum')['state']) return ['state'=>0,'errormsg'=>'您没有权限'];
        if(!$cn) return ['state'=>0,'errormsg'=>'请输入板块名'];
        $data['cn'] = $cn;
        $data['create_time'] = time();
        $data['state'] = 2;
        $data['user_id'] = $this->userId;
        $res = db('forum_label')->insert($data);
        if(!$res) return ['state'=>0,'errormsg'=>'添加失败'];
        return ['state'=>1,'errormsg'=>'成功'];
    }
    //修改板块名
    public function label_rename($label_id,$newname)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if(!model('admin')->is('forum')['state']) return ['state'=>0,'errormsg'=>'您没有权限'];
        if(!$newname) return ['state'=>0,'errormsg'=>'请输入板块名'];
        if(!$label_id) return ['state'=>0,'errormsg'=>'请选择板块'];
        $data['cn'] = $newname;
        $data['user_id'] = $this->userId;
        $res = db('forum_label')->where("label_id = $label_id")->update($data);
        if(!$res) return ['state'=>0,'errormsg'=>'修改失败'];
        return ['state'=>1,'errormsg'=>'成功'];
    }
    //修改板块
//    public function label_modify($label_id,$key,$content)
//    {
//
//    }
    //删除板块
    public function label_remove($label_id)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if(!model('admin')->is('forum')['state']) return ['state'=>0,'errormsg'=>'您没有权限'];
        if(!$label_id) return ['state'=>0,'errormsg'=>'请选择板块'];
        $data['state'] = 0;
        $res = db('forum_label')->where("label_id = $label_id")->update($data);
        if(!$res) return ['state'=>0,'errormsg'=>'修改失败'];
        return ['state'=>1,'errormsg'=>'成功'];
    }
    //开放关闭板块
    public function label_release($label_id,$release)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if(!model('admin')->is('forum')['state']) return ['state'=>0,'errormsg'=>'您没有权限'];
        if(!$label_id) return ['state'=>0,'errormsg'=>'请选择板块'];
        if($release) {
            $data['state'] = 1;
        }else{
            $data['state'] = 2;
        }
        $res = db('forum_label')->where("label_id = $label_id")->update($data);
        if(!$res) return ['state'=>0,'errormsg'=>'关闭失败'];
        return ['state'=>1,'errormsg'=>'成功'];
    }
    //板块列表
    public function label_list($newpost = null,$admin = null)
    {
        if($newpost){
            $list = \db("forum_label")->field('label_id as value,cn as label')->where("state = 1")->cache(true,86400)->select();
            return ['state'=>1,'data'=>['list'=>$list]];
        }
        if($admin){
            $list = db('forum_label')->field('cn,label_id,state,admin')->where("state != 0")->cache(true,8640086400)->select();
            if(!$list) return ['state'=>1,'data'=>[]];
            foreach ($list as $k =>$v){
                if($v['state'] == 1){
                    $list[$k]['released'] = 1;
                }else{
                    $list[$k]['released'] = 0;
                }
            }
            return ['state'=>1,'data'=>['list'=>$list]];
        }
        $list = db('forum_label')->field('cn,label_id')->where("state = 1")->cache(true,86400)->select();
        //找出热门帖子
        $forum_list['hot'] = db('forum')->where("state = 1")->order("reply_amount desc")->limit(0,10)->cache(true,86400)->select();
        $forum_list['top'] = db('forum')->where("state = 1 and top = 1")->order("create_time")->limit(0,10)->cache(true,86400)->select();
        $forum_list['highlight'] = db('forum')->where("state = 1 and highlight = 1")->order("create_time desc")->limit(0,10)->cache(true,86400)->select();
        $forum_list['new'] = db('forum')->where("state = 1")->order("create_time desc")->limit(0,10)->cache(true,86400)->select();
        if(!$list) return ['state'=>1,'data'=>[]];
        foreach ($forum_list['hot']  as $k =>$v){
            $userinfo = model('user')->getInfoById($v['user_id']);
            $forum_list['hot'][$k]['user_name']= isset($userinfo['set_name']) ? $userinfo['set_name'] : $userinfo['user_name'];
        }
        foreach ($forum_list['top']  as $k =>$v){
            $userinfo = model('user')->getInfoById($v['user_id']);
            $forum_list['top'][$k]['user_name']= isset($userinfo['set_name']) ? $userinfo['set_name'] : $userinfo['user_name'];
        }
        foreach ($forum_list['highlight']  as $k =>$v){
            $userinfo = model('user')->getInfoById($v['user_id']);
            $forum_list['highlight'][$k]['user_name']= isset($userinfo['set_name']) ? $userinfo['set_name'] : $userinfo['user_name'];
        }
        foreach ($forum_list['new']  as $k =>$v){
            $userinfo = model('user')->getInfoById($v['user_id']);
            $forum_list['new'][$k]['user_name']= isset($userinfo['set_name']) ? $userinfo['set_name'] : $userinfo['user_name'];
        }
        return ['state'=>1,'data'=>['label'=>$list,'list'=>$forum_list]];

    }
    //设置热门板块
    public function setAdminlabel($label_id,$release)
    {
        if(!model('admin')->is('forum')['state']) return ['state'=>0,'errormsg'=>'您没有权限'];
        if(!$label_id) return ['state'=>0,'errormsg'=>'请选择板块'];

        $data['admin'] = $release;
        $data['set_user_id'] = $this->userId;
        $res = \db('forum_label')->where("label_id = $label_id")->update($data);
        if(!$res) return ['state'=>0,'errrormsg'=>'设置失败'];
        return ['state'=>1,'errormsg'=>'设置成功'];

    }

    //--------------------------帖子管理------------------------------
    //发帖
    public function add($data)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
//        if(!$data['tag']) return ['state'=>0,'errormsg'=>'请填写标签'];
        if(!$data['title']) return ['state'=>0,'errormsg'=>'请填写标题'];
        if(!$data['content'] || $data['content']=="<p><br></p>") return ['state'=>0,'errormsg'=>'请填写内容'];
        if(!$data['label_id']) return ['state'=>0,'errormsg'=>'参数错误'];
        //查询是否是热门板块
        $labelinfo = \db('forum_label')->where("label_id = $data[label_id]")->cache(true,86400)->find();
        if($labelinfo['admin']){
            if(!model('admin')->is('forum')['state']){
                return ['state'=>0,'errormsg'=>'该板块暂未开放发帖权限,请选择其他版块'];
            }
        }
//        if(!$data['tag']) return ['state'=>0,'errormsg'=>'标签必填'];
        $data['state'] = 3; //审核中
        $data['create_time'] = time();
        $data['user_id'] = $this->userId;
        $data['content'] = userTextEncode($data['content']);
        $data['last_reply_time'] = time();
        $res = db('forum')->insertGetId($data);
        if(!$res) return ['state'=>0,'errormsg'=>'发帖失败'];
        //发送通知到版主和管理员
        //查出当前板块的版主
        $m = \db('forum_label')->field('moderator_id')->where("label_id = $data[label_id]")->cache(true,86400)->find();
        $user_id = [];
        if($m && $m['moderator_id']){
            $m = explode(',',$m['moderator_id']);
            foreach ($m as $k =>$v){
                $user_id[] = $v;
            }
        }
        //查询出论坛管理员
        $admin = \db('admin')->field('user_id')->where("class = 7 and state = 1")->cache(true,86400)->select();
        foreach ($admin as $k =>$v){
            $user_id[] = $v['user_id'];
        }
        $user_id = array_unique($user_id);
        foreach ($user_id as $k =>$v){
            $message['value'][$v] = '有待审核帖子帖子需要您的审核';
        }
        $user_id = implode(',',$user_id);
        $message['title'] = '系统消息';
        $message['url'] = "/forum/posts/".$res;
        model('message')->send('forum',$message,$user_id);
        return ['state'=>1,'errormsg'=>'成功'];
    }
    //删帖
    public function remove($forum_id)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if(!$forum_id) return ['state'=>0,'errormsg'=>'请选择帖子'];
        //查询帖子详情
//        $info = \db('forum')->where("forum_id = $forum_id and state != 0 and state !=4")->find();
        $info = \db('forum')->where("forum_id = $forum_id and state != 0")->cache(true,86400)->find();
        if(!$info) return ['state'=>0,'errormsg'=>'未找到该帖子'];

        $data['state'] = 0;
        if(model('admin')->is('forum')['state']){
            $res = db('forum')->where("forum_id = $forum_id")->update($data);
            if(!$res) return ['state'=>0,'errormsg'=>'删除失败'];
            //记录操作
            $action['user_id'] = $this->userId;
            $action['forum_id'] = $forum_id;
            $action['create_time'] = time();
            $action['action'] = 'forum_remove';
            $action['target'] = $forum_id;
            db('forum_action')->insert($action);
            return ['state'=>1,'errormsg'=>"删除成功"];
        }
        $labelinfo = \db('forum_label')->where("label_id = $info[label_id] and state = 1")->cache(true,86400)->find();
        if(!$labelinfo) return ['state'=>0,'errormsg'=>'数据错误'];
        if(in_array($this->userId,explode(',',$labelinfo['moderator_id']))){
            $res = db('forum')->where("forum_id = $forum_id")->update($data);
            if(!$res) return ['state'=>0,'errormsg'=>'删除失败'];
            //记录操作
            $action['user_id'] = $this->userId;
            $action['create_time'] = time();
            $action['action'] = 'forum';
            $action['target'] = $forum_id;
            db('forum_action')->insert($action);
            return ['state'=>1,'errormsg'=>"删除成功"];
        }elseif($this->userId == $info['user_id']){
            $res = db('forum')->where("forum_id = $forum_id")->update($data);
            if(!$res) return ['state'=>0,'errormsg'=>'删除失败'];
            return ['state'=>1,'errormsg'=>"删除成功"];
        }
        return ['state'=>0,'errormsg'=>'您没有权限'];
    }
    //修改帖子
    public function modify($forum_id,$data)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if(!$forum_id) return ['state'=>0,'errormsg'=>'请选择帖子'];
        //判断该帖子是否是审核失败的
        $s = db('forum')->where("forum_id = $forum_id")->cache(true,86400)->find();
        if(!$s) return ['state'=>0,'errormsg'=>'未找到该帖子'];
        if($s['state'] != 4) return ['state'=>0,'errormsg'=>'该帖子不允许被修改'];
        if($s['user_id'] != $this->userId) return ['state'=>0,'errormsg'=>'您不是发帖人,不允许被修改'];
//        if(!$data['tag']) return ['state'=>0,'errormsg'=>'请填写标签'];
        if(!$data['title']) return ['state'=>0,'errormsg'=>'请填写标题'];
        if(!$data['content'] || $data['content']=="<p><br></p>") return ['state'=>0,'errormsg'=>'请填写内容'];
        if(!$data['label_id']) return ['state'=>0,'errormsg'=>'参数错误'];
        //查询是否是热门板块
        $labelinfo = \db('forum_label')->where("label_id = $data[label_id]")->cache(true,86400)->find();
        if($labelinfo['admin']){
            if(!model('admin')->is('forum')['state']){
                return ['state'=>0,'errormsg'=>'该板块暂未开放发帖权限,请选择其他版块'];
            }
        }
//        if(!$data['tag']) return ['state'=>0,'errormsg'=>'标签必填'];
        $data['state'] = 3; //审核中
        $data['create_time'] = time();
        $data['user_id'] = $this->userId;
        $data['content'] = userTextEncode($data['content']);
        $data['last_reply_time'] = time();
        $res = db('forum')->where("forum_id = $forum_id")->update($data);
        if(!$res) return ['state'=>0,'errormsg'=>'修改失败'];
        //发送通知到版主和管理员
        //查出当前板块的版主
        $m = \db('forum_label')->field('moderator_id')->where("label_id = $data[label_id]")->cache(true,86400)->find();
        $user_id = [];
        if($m && $m['moderator_id']){
            $m = explode(',',$m['moderator_id']);
            foreach ($m as $k =>$v){
                $user_id[] = $v;
            }
        }
        //查询出论坛管理员
        $admin = \db('admin')->field('user_id')->where("class = 7 and state = 1")->cache(true,86400)->select();
        foreach ($admin as $k =>$v){
            $user_id[] = $v['user_id'];
        }
        $user_id = array_unique($user_id);
        foreach ($user_id as $k =>$v){
            $message['value'][$v] = '有待审核帖子帖子需要您的审核';
        }
        $user_id = implode(',',$user_id);
        $message['title'] = '系统消息';
        $message['url'] = "/forum/posts/".$res;
        model('message')->send('forum',$message,$user_id);
        return ['state'=>1,'errormsg'=>'成功'];
    }
    //获取列表
    public function forum_list($filter)
    {
        //基础条件
        if (isset($filter['page']) && $filter['page'] != '') {
            $pages = $filter['page'];
        }else{
            $pages = 1;
        }
        if(isset($filter['type'])&&$filter['type'] == 'apply') {
            if($filter['label_id']){
                $list = db('forum')->field('forum_id,title,label_id,user_id,create_time,content,tag')->where("state = 3 and label_id = $filter[label_id]")->order('create_time')->cache(true,86400)->paginate(12,false,['page'=>$pages]);
            }else{
                $list = db('forum')->field('forum_id,title,label_id,user_id,create_time,content,tag')->where("state = 3")->order('create_time')->cache(true,86400)->paginate(12,false,['page'=>$pages]);
            }
            $page = $list->lastPage();
            $list = $list->items();
            $label_name = db('forum_label')->where("state = 1")->cache(true,86400)->select();
            foreach ($list as $k => $v) {
                foreach ($label_name as $kk =>$vv){
                    if($v['label_id'] ==$vv['label_id']){
                        $list[$k]['cn'] = $vv['cn'];
                    }
                }
                $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                $user_info = model('user')->getInfoById($v['user_id']);
                $list[$k]['tel'] = db('user_tel')->where("user_id = $v[user_id] and state = 1")->find()['tel'];
                $list[$k]['user_name'] = isset($user_info['set_name']) ? $user_info['set_name'] : $user_info['user_name'];
//                $list[$k]['content'] = htmlspecialchars_decode(userTextDecode($v['content']));
                $list[$k]['headimgurl'] = $user_info['headimgurl'];
            }

            if (!$list) return ['state' => 1, 'data' => []];
            return ['state' => 1, 'data' => ['list' => $list],'page'=>$page];
        }

        if($filter['label_id']){
            $where = "state = 1 and label_id = $filter[label_id]";
            $order = ['top'=>'desc','last_reply_time'=>'desc','create_time'=>'desc'];
            switch ($filter['type']){
                case 'create_time':
                    $order = ['create_time'=>'desc'];
                    break;
                case 'browse':
                    $order = ['browse'=>'desc'];
                    break;
                case 'reply_amount':
                    $order = ['reply_amount'=>'desc'];
                    break;
            }

            if($this->userId) {
                $where .= " or (state !=0 and label_id = $filter[label_id] and user_id = $this->userId and state !=4)";
            }
            $list = db('forum')->field('content,reason,state',true)->where($where)->order($order)->cache(true,86400)->paginate(20,false,['page'=>$pages]);
            $page = $list->total();
            $list = $list->items();

            foreach ($list as $k =>$v){
                $user_info = model('user')->getInfoById($v['user_id']);
                $list[$k]['user_name'] = isset($user_info['set_name']) ? $user_info['set_name'] : $user_info['user_name'];
                $list[$k]['headimgurl'] = $user_info['headimgurl'];
                $forum_reply = db('forum_reply')->where("forum_id = $v[forum_id] and state = 1")->order('create_time desc')->find();
                $list[$k]['last_user_id'] = $forum_reply['user_id'];
                $last_user_name = model('user')->getInfoById($list[$k]['last_user_id']);
                $list[$k]['last_user_name'] = isset($last_user_name['set_name']) ? $last_user_name['set_name'] : $last_user_name['user_name'];
                if($forum_reply['create_time']) {
                    $list[$k]['last_time'] = date('Y-m-d', $forum_reply['create_time']);
                }
                $list[$k]['create_time'] = date('Y-m-d',$v['create_time']);
//                $list[$k]['content'] = htmlspecialchars_decode(userTextDecode($v['content']));
            }
            //查询论坛版块
            $info = db('forum_label')->field('cn,label_id')->where("label_id = $filter[label_id] and state = 1")->cache(true,86400)->find();
            if(!$info) return ['state'=>1,'data'=>[]];
            //查询主题数和回复数
            $forum = db('forum')->field('reply_amount')->where("label_id = $filter[label_id] and state = 1")->cache(true,86400)->select();
            $info['count'] = count($forum);
            foreach($forum as $k =>$v){
                isset($info['reply_amount']) ? $info['reply_amount'] = $info['reply_amount']+$v['reply_amount']:$info['reply_amount'] = $v['reply_amount'];
            }
            if($this->userId) {
                //判断该用户是否是版主
                $label = \db('forum_label')->where("label_id = $filter[label_id] and moderator_id like '%$this->userId%'")->cache(true,86400)->find();
                if ($label) {
                    $info['moderator'] = 1;
                }
            }
            if(model('admin')->is('forum')['state']){
                $info['moderator'] = 1;
            }
            return ['state'=>1,'data'=>['list'=>$list,'info'=>$info],'page'=>$page];
        }else{
            $order = ['last_reply_time'=>'desc','create_time'=>'desc'];
            switch ($filter['type']){
                case 'create_time':
                    $order = ['create_time'=>'desc'];
                    break;
                case 'browse':
                    $order = ['browse'=>'desc'];
                    break;
                case 'reply_amount':
                    $order = ['reply_amount'=>'desc'];
                    break;
            }
            switch ($filter['type']){
                case 'create_time_asc':
                    $order = ['create_time'=>'asc'];
                    break;
                case 'browse_asc':
                    $order = ['browse'=>'asc'];
                    break;
                case 'reply_amount_asc':
                    $order = ['reply_amount'=>'asc'];
                    break;
            }
            $list = db('forum')->where('state = 1')->order($order)->cache(true,86400)->paginate(12,false,['page'=>$pages]);
            $page = $list->total();
            $list = $list->items();

            $label_name = db('forum_label')->where("state = 1")->cache(true,86400)->select();
            foreach ($list as $k =>$v){
                foreach ($label_name as $kk =>$vv){
                    if($v['label_id'] ==$vv['label_id']){
                        $list[$k]['cn'] = $vv['cn'];
                    }
                }
                $user_info = model('user')->getInfoById($v['user_id']);
                $list[$k]['user_name'] = isset($user_info['set_name']) ? $user_info['set_name'] : $user_info['user_name'];
                $list[$k]['tel'] = db('user_tel')->where("user_id = $v[user_id] and state = 1")->find()['tel'];
                $forum_reply = db('forum_reply')->where("forum_id = $v[forum_id] and state = 1")->order('create_time desc')->find();
                $list[$k]['last_user_id'] = $forum_reply['user_id'];
                $last_user_name = model('user')->getInfoById($list[$k]['last_user_id']);
                $list[$k]['last_user_name'] = isset($last_user_name['set_name']) ? $last_user_name['set_name'] : $last_user_name['user_name'];
                if($forum_reply['create_time']) {
                    $list[$k]['last_time'] = date('Y-m-d', $forum_reply['create_time']);
                }
                $list[$k]['create_time'] = date('Y-m-d',$v['create_time']);
            }
            return ['state'=>1,'data'=>['list'=>$list],'page'=>$page];
        }
    }
    //回帖
    public function reply($data)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if(!$data['forum_id']) return ['state'=>0,'errormsg'=>'参数错误'];
        if(!$data['content']) return ['state'=>0,'errormsg'=>'请输出回复内容'];
        //判断是内容是否超过10个汉字
        if(preg_match_all("/[\x{4e00}-\x{9fa5}]/u", $data['content'], $matches)<10){
            return ['state'=>0,'errormsg'=>'内容不得小于10个字'];
        }
        //判断是否是未审核
        $apply = db('forum')->where("forum_id = $data[forum_id]")->cache(true,86400)->find();
        if($apply['state']!==1){
            return ['state'=>0,'errormsg'=>'不能评论未开放的帖子'];
        }
        $data['user_id'] = $this->userId;
        $data['create_time'] = time();
        $data['state'] = 1;
        $data['content'] = htmlentities(userTextEncode($data['content']));
        //获取楼层id
        $data['floor_id'] = db("forum_reply")->field("floor_id")->where("forum_id = $data[forum_id]")->order("create_time desc")->find()['floor_id']+1;
        $res = db('forum_reply')->insert($data);
        db('forum')->where("forum_id = $data[forum_id]")->setInc('reply_amount',1);
        db('forum')->where("forum_id = $data[forum_id]")->update(['last_reply_time'=>time()]);
        if(!$res) return ['state'=>0,'errormsg'=>'回复失败'];
        //获得积分
        $state = $this->check_points();
        if(!$state['state']) return ['state'=>1,'errormsg'=>'ok'];
        //判断是否是回复同一帖子
        $t = time();
        $start = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
        $end = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));
        $points = db('forum_points_rule')->where('way = 3')->find();
        if($points['upper_limit']){
            $data['amount'] = $points['amount'];
            if($points['upper_limit'] - $state['amount'] <$points['amount']){
                $data['amount'] = $points['upper_limit'] - $state['amount'];
            }
        }else{
            $data['amount'] = $points['amount'];
        }
        $data['way'] = 3;
        db('forum_points')->insert($data);
        //判断是否得到额外积分
        $res = db('forum_points')->field('forum_id')->where("user_id = $this->userId")->where("create_time >$start and create_time <$end and way = 3")->select();
        //取得不同帖子的个数
        $id = [];
        foreach ($res as $k =>$v){
            $id[] = $v['forum_id'];
        }
        $id = count(array_unique($id));
        if(is_int($id/$points['frequency'])){
            $e['way'] = 5;
            $e['create_time'] = time();
            $e['state'] = 1;
            $e['user_id'] = $this->userId;
            //判断积分是否达到上限
            if($points['upper_limit']){
                $e['amount'] = $points['integral'];
                if($points['upper_limit'] - $state['amount'] <$points['integral']){
                    $e['amount'] = $points['upper_limit'] - $state['amount'];
                }
            }else{
                $e['amount'] = $points['integral'];
            }
            db('forum_points')->insert($e);
        }
        //判断是否为用户回复
        $info = db('forum')->where("forum_id = $data[forum_id]")->find();
        $user_info = model('user')->getInfoById($this->userId);
        $user_name = isset($user_info['set_name']) ? $user_info['set_name'] : $user_info['user_name'];
        if($info['user_id'] != $this->userId){
            //被回复人增加积分
            //判断被回复人积分是否达上限
            $state = $this->check_points($info['user_id']);
            if($state['state']){
                $a['user_id'] = $info['user_id'];
                $a['state'] = 1;
                $a['create_time'] = time();
                $a['forum_id'] = $data['forum_id'];
                if($points['upper_limit']){
                    $a['amount'] = $points['amount'];
                    if($points['upper_limit'] - $state['amount'] <$points['amount']){
                        $a['amount'] = $points['upper_limit'] - $state['amount'];
                    }
                }else{
                    $a['amount'] = $points['amount'];
                }
                db('forum_points')->insert($a);
            }

            $message['value'][$info['user_id']] = $user_name.'回复了您的帖子 ['.$apply['title'].']';
            $message['title'] = '您有新的回复内容';
            $message['url'] = '/forum/posts/'.$data['forum_id'];
            model('message')->send('forum',$message,$info['user_id']);
        }
        //发送系统信息
        if($data['pid']){
            $user_id = db('forum_reply')->where("reply_id = $data[pid]")->find()['user_id'];
            if($user_id != $this->userId){
                $message['value'][$user_id] = $user_name.'回复了您的评论';
                $message['title'] = '您有新的回复内容';
                $message['url'] = '/forum/posts/'.$data['forum_id'];
                model('message')->send('forum',$message,$user_id);
            }
        }
        return ['state'=>1,'errormsg'=>'ok'];
    }
    //回复列表
    public function reply_list()
    {
        if(!$this->userId)return ['state'=>0,'errormsg'=>'请登录'];
        $reply = db('forum_reply')->where("user_id = $this->userId and state = 1")->select();
        if(!$reply) return ['satte'=>1,'data'=>[]];
        foreach ($reply as $k =>$v){
            $forum = \db('forum')->field('title')->where("forum_id = $v[forum_id] and state = 1")->find();
            if(!$forum) unset($reply[$k]);
            $reply[$k]['title'] = $forum['title'];
        }
        if(!$reply) return ['state'=>1,'data'=>[]];
        return ['state'=>1,'data'=>['list'=>$reply]];
    }
    //删除回复
    public function reply_remove($reply_id)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if(!$reply_id) return ['state'=>0,'errormsg'=>'请选择帖子'];
        //查询帖子详情
        $info = \db('forum_reply')->where("reply_id = $reply_id and state != 0")->cache(true,86400)->find();
        if(!$info) return ['state'=>0,'errormsg'=>'未找到该回复'];
        $foruminfo = \db('forum')->where("forum_id = $info[forum_id] and state != 0 and state !=4")->cache(true,86400)->find();
        if(!$foruminfo) return ['state'=>0,'errormsg'=>'未找到该帖子'];
        $labelinfo = \db('forum_label')->where("label_id = $foruminfo[label_id] and state = 1")->cache(true,86400)->find();
        if(!$labelinfo) return ['state'=>0,'errormsg'=>'数据错误'];
        $data['state'] = 0;
        if(model('admin')->is('forum')['state']){
            $res = \db('forum_reply')->where("reply_id = $reply_id")->update($data);
            if(!$res) return ['state'=>0,'errormsg'=>'删除失败'];
            return ['state'=>1,'errormsg'=>"删除成功"];
        }
        if(in_array($this->userId,explode(',',$labelinfo['moderator_id']))){
            $res = \db('forum_reply')->where("reply_id = $reply_id")->update($data);
            if(!$res) return ['state'=>0,'errormsg'=>'删除失败'];
            //记录操作
            $action['user_id'] = $this->userId;
            $action['create_time'] = time();
            $action['action'] = 'reply_remove';
            $action['target'] = $reply_id;
            db('forum_action')->insert($action);
            return ['state'=>1,'errormsg'=>"删除成功"];
        }elseif($this->userId == $info['user_id']){
            $res = \db('forum_reply')->where("reply_id = $reply_id")->update($data);
            if(!$res) return ['state'=>0,'errormsg'=>'删除失败'];
            return ['state'=>1,'errormsg'=>"删除成功"];
        }
        return ['state'=>0,'errormsg'=>'您没有权限'];
    }
    //点赞
    public function fabulous($data)
    {
        if(!$data['forum_id']) return ['state'=>0,'errormsg'=>'参数错误'];
        //判断当前用户是否赞过
        $data['ip_address'] = getIp();
        $user_id = $this->userId;
        if($user_id){
            $info = db('forum_fabulous')->where("forum_id = $data[forum_id] and (ip_address = '$data[ip_address]' or user_id  = $user_id)")->find();
        }else{
            $info = db('forum_fabulous')->where("forum_id = $data[forum_id] and ip_address = '$data[ip_address]'")->find();
        }
        if($info) return ['state'=>0,'errormsg'=>'已经赞过'];
        if($this->userId){
            $data['user_id'] = $this->userId;
        }else{
            $data['user_id'] = null;
        }
        $data['create_time'] = time();
        $res = db('forum_fabulous')->insert($data);
        if(!$res) return ['state'=>0,'errormsg'=>'失败'];
        $id = db('forum')->where("forum_id = $data[forum_id]")->setInc('fabulous');
        $amount = db('forum')->where("forum_id = $data[forum_id]")->find()['fabulous'];
        return ['state'=>1,'data'=>['fabulous'=>$amount]];
    }
    //转移板块
    public function changelabel($data)
    {
        if(!$data['forum_id']) return ['state'=>0,'errormsg'=>'参数错误'];
        if(!$data['label_id']) return ['state'=>0,'errormsg'=>'参数错误'];
        $label = db("forum")->alias('f')->join("forum_label l","f.label_id = l.label_id")
            ->field("moderator_id,cn")
            ->where("f.state = 1 and l.state = 1 and forum_id = $data[forum_id]")
            ->cache(true,86400)
            ->find();
        if(!model('admin')->is('forum')['state']){
            //查询操作者是否有权限
            if(!$label) return ['state'=>0,'errormsg'=>'您没有权限'];
            $moderator_id = explode(',',$label['moderator_id']);
            if(!in_array($this->userId,$moderator_id)){
                return ['state'=>0,'errormsg'=>'您没有权限'];
            }
        }
        $adminuserinfo = model('user')->getInfoById($this->userId);
        $adminusername = isset($adminuserinfo['set_name']) ? $adminuserinfo['set_name'] : $adminuserinfo['user_name'];
        $_data['label_id'] = $data['label_id'];
        $_data['admin_user_id'] = $this->userId;
        $forum = \db("forum")->where("forum_id = $data[forum_id]")->update($_data);
        if(!$forum) return ['state'=>0,'errormsg'=>'转移失败,请重试'];
        $message['value'][$forum['user_id']] = '您的帖子 ['.$forum['title'].'] 被管理员: '.$adminusername.' 转移至 ['.$label['cn'].'] 板块';
        $message['title'] = '系统消息';
        $message['url'] = "/forum/posts/$data[forum_id]";
        model('message')->send('forum',$message,$forum['user_id']);
        return ['state'=>1,'errormsg'=>'转移成功'];
    }

    //根据id获取帖子详情
    public function getInfo($forum_id,$page = 1)
    {
        if(!$forum_id) return ['state'=>0,'errormsg'=>'请选择一个帖子'];
        $info = db('forum')->field('reason',true)->where("forum_id = $forum_id")->cache(true,86400)->find();
        //判断该用户是否是版主
        $label = \db('forum_label')->field('moderator_id')->where("label_id = $info[label_id]")->cache(true,86400)->find();
        $moderator_id = explode(',',$label['moderator_id']);

        if(!$this->userId){
            $info = db('forum')->field('reason',true)->where("forum_id = $forum_id and state = 1")->cache(true,86400)->find();
        }else{
            if(in_array($this->userId,$moderator_id) || model('admin')->is('forum')['state']){
                $info = db('forum')->field('reason',true)->where("forum_id = $forum_id and state !=0")->cache(true,86400)->find();
                if(!$info) return ['state'=>0,'errormsg'=>'该帖子已被删除'];
                $info['moderators'] = 1;
            }else{
                $info = db('forum')->field('reason',true)->where("forum_id = $forum_id and state = 1 or (forum_id = $forum_id and user_id = $this->userId and state !=0)")->cache(true)->find();
            }
        }
        if(!$info) return ['state'=>0,'errormsg'=>'该帖子已被删除'];
        //查询页数
        $user_info = model('user')->getInfoById($info['user_id']);
        $info['user_name'] = isset($user_info['set_name']) ? $user_info['set_name'] : $user_info['user_name'];
        //查询帖子数
        $info['forum_amount'] = db('forum')->where("user_id = $info[user_id] and state = 1")->count();
        $info['headimgurl'] = db('user')->where("user_id = $info[user_id]")->cache(true)->find()['headimgurl'];
        $info['label_name'] = db('forum_label')->where("label_id = $info[label_id]")->cache(true)->find()['cn'];
        $info['content'] =htmlspecialchars_decode($info['content']);
        //替换成现在api
        $info['content'] = str_replace("www.hongyanche.com",'file.hongyanche.com',$info['content']);
        $info['content'] = str_replace("admin.hongyanche.com",'file.hongyanche.com',$info['content']);
        $info['create_time'] = date('Y-m-d H:i:s', $info['create_time']);
        if($info['last_reply_time']){
            $info['last_reply_time'] = date('Y-m-d H:i:s', $info['last_reply_time']);
        }else{
            unset($info['last_reply_time']);
        }
        //获取精华帖总数
        $info['highlight_amount'] = \db('forum')->where("state = 1 and highlight = 1")->count(1);
        //获取积分
        $ponits = db('forum_points')->field('sum(amount) as amount')->where("user_id = $info[user_id]")->select()[0]['amount'];
        $info['points'] = $ponits ? $ponits : 0;
        $empirical_value = db('forum_points')->field('sum(amount) as amount')->where("user_id = $info[user_id] and amount>0")->select()[0]['amount'];
        //判断等级
        if ($empirical_value < 50) {
            $info['empirical_value'] = 'LV1';
        } elseif ($empirical_value >= 50 && $empirical_value < 300) {
            $info['empirical_value'] = 'LV2';
        } elseif (($empirical_value >= 300 && $empirical_value < 500)) {
            $info['empirical_value'] = 'LV3';
        } elseif ($empirical_value >= 500 && $empirical_value < 5000) {
            $info['empirical_value'] = 'LV4';
        } elseif ($empirical_value >= 5000) {
            $info['empirical_value'] = 'LV5';
        }
        if($info['state'] == 3){
            $info['apply'] = true;
        }
        $info['highlight'] ? $info['highlight'] = true:$info['highlight'] = false;
        $info['top']?$info['top'] = true:$info['top'] = false;
        db('forum')->where("forum_id = $forum_id")->setInc('browse');
        $data['forum_id'] = $forum_id;
        $data['create_time'] = time();
        $data['state'] = 1;
        db('forum_browse')->insert($data);
        $info['reply'] = db('forum_reply')->field('state',true)
            ->where("forum_id = $forum_id and state = 1")->paginate(12,false,['page'=>$page]);
        $pages = $info['reply']->total();
        $info['reply'] = $info['reply']->items();
        foreach ($info['reply'] as $k =>$v){
//            //判断回帖人是否是版主
//            if(in_array($v['user_id'],$moderator_id)){
//                $info['reply'][$k]['moderator'] = 1;
//            }
            if($this->userId == $v['user_id']){
                $info['reply'][$k]['moved'] = 1;
            }
            //判断当前用户是否是版主
            if($this->userId && in_array($this->userId,$moderator_id)){
                $info['reply'][$k]['moved'] = 1;
            }
            if(model('admin')->is('forum')['state']){
                $info['reply'][$k]['moved'] = 1;
            }

            if($v['pid']) {
                $received = db('forum_reply')->field('user_id,content')->where("floor_id = $v[pid] and forum_id = $v[forum_id] and state = 1")->find();
                if ($received) {
                    $pregRule = "/<img\b[^>]*>/";
                    $iframe = "/<iframe\b[^>]*><\\/iframe>/";
                    $embed = "/<embed\b[^>]*>/";
                    preg_match_all($pregRule, htmlspecialchars_decode($received['content']), $im);
                    preg_match_all($iframe, htmlspecialchars_decode($received['content']), $if);
                    preg_match_all($embed, htmlspecialchars_decode($received['content']), $em);
                    if ($im[0]) {
                        $info['reply'][$k]['received_content'] = str_replace($im[0], '[图片]', htmlspecialchars_decode($received['content']));
                    } else if ($if[0]) {
                        $info['reply'][$k]['received_content'] = str_replace($if[0], '[视频]', htmlspecialchars_decode($received['content']));
                    } else if ($em[0]) {
                        $info['reply'][$k]['received_content'] = str_replace($em[0], '[视频]', htmlspecialchars_decode($received['content']));
                    } else {
                        $info['reply'][$k]['received_content'] = htmlspecialchars_decode($received['content']);
                    }
                    $received_username = model('user')->getInfoById($v['user_id']);
                    $info['reply'][$k]['received_username'] = isset($received_username['set_name']) ? $received_username['set_name'] : $received_username['user_name'];
                    $info['reply'][$k]['received_headimgurl'] = db('user')->where("user_id = $v[user_id]")->cache(true)->find()['headimgurl'];
                }
            }
            $info['reply'][$k]['forum_amount'] = db('forum')->where("user_id = $v[user_id] and state = 1")->count();
            $info['reply'][$k]['headimgurl'] = db('user')->where("user_id = $v[user_id]")->cache(true)->find()['headimgurl'];
            $user_info = model('user')->getInfoById($v['user_id']);
            $info['reply'][$k]['user_name'] = isset($user_info['set_name']) ? $user_info['set_name'] : $user_info['user_name'];
            $info['reply'][$k]['content'] = htmlspecialchars_decode(userTextDecode($v['content']));
            //替换成现在api
            $info['reply'][$k]['content'] = str_replace("www.hongyanche.com",'file.hongyanche.com',$info['reply'][$k]['content']);
            $info['reply'][$k]['content'] = str_replace("admin.hongyanche.com",'file.hongyanche.com',$info['reply'][$k]['content']);
            $info['reply'][$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            //获取积分
            $ponits=db('forum_points')->field('sum(amount) as amount')->where("user_id = $v[user_id]")->select()[0]['amount'];
            $info['points'] = $ponits?$ponits:0;
            $empirical_value = db('forum_points')->field('sum(amount) as amount')->where("user_id = $v[user_id] and amount>0")->select()[0]['amount'];
            //判断等级
            if($empirical_value<50){
                $info['reply'][$k]['empirical_value'] = 'LV1';
            }elseif($empirical_value>=50 && $empirical_value<300){
                $info['reply'][$k]['empirical_value'] = 'LV2';
            }elseif (($empirical_value>=300 && $empirical_value<500)){
                $info['reply'][$k]['empirical_value'] = 'LV3';
            }elseif ($empirical_value>=500 && $empirical_value<5000){
                $info['reply'][$k]['empirical_value'] = 'LV4';
            }elseif ($empirical_value>=5000){
                $info['reply'][$k]['empirical_value'] = 'LV5';
            }
        }
        if(!$info) return ['state'=>1,'data'=>[]];
        return ['state'=>1,'data'=>['info'=>$info],'page'=>$pages];
    }
    //签到
    public function sign()
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        $t = time();
        $start = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
        $end = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));
        $state = $this->check_points();
        if(!$state['state']) return ['state'=>0,'errormsg'=>'今日积分已达上限'];
        //判断是否签到过
        $sign = db('forum_points')->field('sum(amount) as amount')->where("user_id = $this->userId and way = 1")->where("create_time >$start and create_time <$end")->find();
        if($sign['amount']) return ['state'=>0,'errormsg'=>'今日已签过到'];
        $res = db('forum_points')->field('sum(amount) as amount')->where("user_id = $this->userId")->where("create_time >$start and create_time <$end")->select();
        //查询积分
        $points = \db('forum_points_rule')->where('way = 1')->find();
        $data['user_id'] = $this->userId;
        $data['way'] = 1;
        $data['state'] = 1;
        $data['create_time'] = time();
        $data['amount'] = $points['amount'];
        //判断积分是否达到上限
        if($points['upper_limit']){
            if($points['upper_limit'] - $state['amount'] <$points['amount']){
                $data['amount'] = $points['upper_limit'] - $state['amount'];
            }
        }
        $res = db('forum_points')->insert($data);
        if(!$res) return ['state'=>0,'errormsg'=>'签到失败'];
        return ['state'=>1,'errormsg'=>'签到成功'];
    }
    //判断积分是否达上限
    public function check_points($user_id = null)
    {
        //判断是否签到过
        if($user_id){
            $userid = $user_id;
        }else{
            $userid = $this->userId;
        }
        $t = time();
        $start = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
        $end = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));
        $res = db('forum_points')->field('sum(amount) as amount')->where("user_id = $userid")->where("create_time >$start and create_time <$end")->find();
        $points = db('forum_points_rule')->where('state = 1')->find();
        //limit为假
        if($points['upper_limit']){
            if($res['amount']>=$points['upper_limit']){
                return ['state'=>0,'errormsg'=>'当日积分已达上限'];
            }
        }
        return ['state'=>1,'amount' =>$res['amount']];
    }
    //加精
    public function highlight($forum_id,$highlight)
    {
        if(!$this->userId)return ['state'=>0,'errormsg'=>'请登录'];
        if(!$forum_id) return ['state'=>0,'errormsg'=>'请选择帖子'];
        //查询帖子详情
        $info = db('forum')->where("forum_id = $forum_id and state != 0 and state !=4")->cache(true,86400)->find();
        if(!$info) return ['state'=>0,'errormsg'=>'未找到该帖子'];
        $labelinfo = \db('forum_label')->where("label_id = $info[label_id] and state = 1")->cache(true,86400)->find();
        if(!$labelinfo) return ['state'=>0,'errormsg'=>'数据错误'];
        $data['highlight'] = $highlight;
        if(model('admin')->is('forum')['state']){
            $res = db('forum')->where("forum_id = $forum_id")->update($data);
            if(!$res) return ['state'=>0,'errormsg'=>'失败'];
            //记录操作
            $action['user_id'] = $this->userId;
            $action['create_time'] = time();
            $action['action'] = 'highlight';
            $action['target'] = $forum_id;
            db('forum_action')->insert($action);
            return ['state'=>1,'errormsg'=>"成功"];
        }
        if(in_array($this->userId,explode(',',$labelinfo['moderator_id']))){
            $res = db('forum')->where("forum_id = $forum_id")->update($data);
            if(!$res) return ['state'=>0,'errormsg'=>'失败'];
            //记录操作
            $action['user_id'] = $this->userId;
            $action['create_time'] = time();
            $action['action'] = 'highlight';
            $action['target'] = $forum_id;
            db('forum_action')->insert($action);
            return ['state'=>1,'errormsg'=>"成功"];
        }
        return ['state'=>0,'errormsg'=>'您没有权限'];
    }
    //置顶
    public function top($forum_id,$top)
    {
        if(!$this->userId)return ['state'=>0,'errormsg'=>'请登录'];
        if(!$forum_id) return ['state'=>0,'errormsg'=>'请选择帖子'];
        //查询帖子详情
        $info = db('forum')->where("forum_id = $forum_id and state != 0 and state !=4")->cache(true,86400)->find();
        if(!$info) return ['state'=>0,'errormsg'=>'未找到该帖子'];
        $labelinfo = \db('forum_label')->where("label_id = $info[label_id] and state = 1")->cache(true,86400)->find();
        if(!$labelinfo) return ['state'=>0,'errormsg'=>'数据错误'];
        $data['top'] = $top;
        if(model('admin')->is('forum')['state']){
            $res = db('forum')->where("forum_id = $forum_id")->update($data);
            if(!$res) return ['state'=>0,'errormsg'=>'失败'];
            //记录操作
            $action['user_id'] = $this->userId;
            $action['create_time'] = time();
            $action['action'] = 'top';
            $action['target'] = $forum_id;
            db('forum_action')->insert($action);
            return ['state'=>1,'errormsg'=>"成功"];
        }
        if(in_array($this->userId,explode(',',$labelinfo['moderator_id']))){
            $res = db('forum')->where("forum_id = $forum_id")->update($data);
            if(!$res) return ['state'=>0,'errormsg'=>'失败'];
            //记录操作
            $action['user_id'] = $this->userId;
            $action['create_time'] = time();
            $action['action'] = 'top';
            $action['target'] = $forum_id;
            db('forum_action')->insert($action);
            return ['state'=>1,'errormsg'=>"成功"];
        }
        return ['state'=>0,'errormsg'=>'您没有权限'];
    }

    //--------------------------申请管理------------------------------
    //申请列表
    public function apply_list($filter)
    {
        if(!model('admin')->is('forum')['state']) return ['state'=>0,'errormsg'=>'您没有权限'];
        //基础条件
        if (isset($filter['page']) && $filter['page'] != '') {
            $page = $filter['page'];
        }else{
            $page = 1;
        }

        $list = db('forum')->where("state = 3")->order('create_time')->cache(true,86400)->paginate(12,false,['page'=>$page]);
        $pages = $list->render();
        $list = $list->items();
        $pages=preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)","<a href='javascript:ajax_page($1);'>$2</a>",$pages);
        $pages=str_replace("&laquo;","上一页",$pages);
        $pages=str_replace("&raquo;","下一页",$pages);

        foreach ($list as $k =>$v){
            $list[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            $user_info = model('user')->getInfoById($v['user_id']);
            $list[$k]['user_name'] = isset($user_info['set_name']) ? $user_info['set_name'] : $user_info['user_name'];
        }
        if(!$list) return ['state'=>1,'data'=>[]];
        return ['state'=>1,'data'=>['list'=>$list],'page'=>$pages];

    }
    //审核
    public function apply_dispose($forum_id,$approve,$reason,$label_id = null)
    {
        if(!$forum_id) return ['state'=>0,'errormsg'=>'请选择一个帖子'];
        if($approve){
            $data['state'] = 1;
        }else{
            $data['state'] = 4;
        }
        if($reason){
            $data['reason'] = $reason;
        }
        if($label_id){
            $data['label_id'] = $label_id;
        }
        //判断当前用户是否是管理员或者版主
        if(!model('admin')->is('forum')['state']){
            //查出当天帖子的label
            $labelid = db('forum')->field('label_id')->where("forum_id = $forum_id")->cache(true,86400)->find();
            if(!$labelid) return ['state'=>0,'errormsg'=>'操作失败'];
            $label = \db('forum_label')->where("label_id = $labelid[label_id] and moderator_id like '%$this->userId%'")->cache(true,86400)->find();
            if(!$label) return ['state'=>0,'errormsg'=>'您没有权限'];
        }
        $data['admin_user_id'] = $this->userId;
        $res = db('forum')->where("forum_id = $forum_id")->update($data);
        if(!$res) return ['state'=>0,'errormsg'=>'操作失败'];
        $forum = db('forum')->where("forum_id = $forum_id")->cache(true,86400)->find();
        //查询积分
        $points = \db('forum_points_rule')->where("way = 4")->find();
        if($data['state'] == 1){
            //获得user_id
            //获得积分
            $state = $this->check_points($forum['user_id']);
            if(!$state['state']) return ['state'=>1,'errorsmg'=>'发帖成功'];
//            $t = time();
//            $start = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
//            $end = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));
//            $res = db('forum_points')->field('sum(amount) as amount')->where("forum_id = $forum_id and user_id = $forum[user_id]")->where("create_time >$start and create_time <$end")->select();
            //判断积分是否达到上限
            $data['amount'] = $points['amount'];
            if($points['upper_limit']){
                if($points['upper_limit'] - $state['amount'] <$points['amount']){
                    $data['amount'] = $points['upper_limit'] - $state['amount'];
                }
            }
            $data['user_id'] = $forum['user_id'];
            $data['forum_id'] = $forum_id;
            $data['way'] = 4;
            $data['create_time'] = time();
            $data['url'] = "/forum/posts/".$forum_id;
            db('forum_points')->insert($data);
            if($label_id){
                $cn = \db('forum_label')->field('cn')->where("label_id = $label_id")->cache(true,86400)->find()['cn'];
                $message['value'][$forum['user_id']] = '您的帖子 ['.$forum['title'].'] 已通过审核,并被转移至 ['.$cn.'] 板块';
            }else{
                $message['value'][$forum['user_id']] = '您的帖子 ['.$forum['title'].'] 已通过审核';
            }
            $message['title'] = '系统消息';
            $message['url'] = "/forum/posts/".$forum_id;
            model('message')->send('forum',$message,$forum['user_id']);
        }else{
            if($label_id){
                $cn = \db('forum_label')->field('cn')->where("label_id = $label_id")->cache(true,86400)->find()['cn'];
                $message['value'][$forum['user_id']] = '您的帖子 ['.$forum['title'].'] 审核失败,并被转移至 ['.$cn.'] 板块,原因:'.$reason.',请修改内容后重新提交申请';
            }else{
                $message['value'][$forum['user_id']] = '您的帖子 ['.$forum['title'].'] 审核失败,原因:'.$reason.',请修改内容后重新提交申请';
            }
            $message['url'] = "/forum/posts/".$forum_id;
            $message['title'] = '系统消息';
            model('message')->send('forum',$message,$forum['user_id']);
        }
        return ['state'=>1,'errormsg'=>'ok'];

    }

    //--------------------------版主管理------------------------------
    //版主邀请
    public function invite_moderator($tel,$label_id)
    {
        if(!$tel) return ['state'=>0,'errormsg'=>'请输入电话号码'];
        if(!$label_id) return ['state'=>0,'errormsg'=>'请选择板块'];
        //查询user_id
        $user_id = db('user_tel')->where("tel = $tel and state = 1")->cache(true,86400)->find();
        if(!$user_id) return ['state'=>0,'errormsg'=>'该电话号码未注册'];
        //判断label_id是否有效
        $label_info = db('forum_label')->where("label_id = $label_id and state = 1")->cache(true,86400)->find();
        if(!$label_info) return ['state'=>0,'errormsg'=>'该板块无效'];
        //信息都有效 执行通知
        $message['value'][$user_id['user_id']] = "邀请您作为 [$label_info[cn]] 板块的版主";
        $message['title'] = '系统消息';
        $message['url'] = "$label_info[label_id]";
        model('message')->send('forum',$message,$user_id['user_id']);
        return ['state'=>1,'errormsg'=>'发送成功'];
    }
    //版主邀请确认
    public function moderator_confirm($label_id)
    {
        header('Content-type:text/html;charset=utf-8');
        //确认该用户是否收到邀请
        if(!$this->userId) {
            return ['state'=>0,'errormsg'=>'请登录'];
        }
        if(!$label_id){
            return ['state'=>0,'errormsg'=>'参数错误'];
        }
        if(!is_numeric($label_id)) {
            return ['state'=>0,'errormsg'=>'参数错误'];
        }
        $message = db('message')->where("receiver = $this->userId and state = 1 and url = $label_id")->order('create_time desc')->find();
        if(!$message){
            return ['state'=>0,'errormsg'=>'您未收到邀请'];
        }
        if(time()-$message['create_time']>=strtotime("-1 month")){
            return ['state'=>0,'errormsg'=>'邀请过期'];
        }else{
            $res  = db('forum_label')->where("label_id = $label_id and state = 1")->cache(true,86400)->find();
            if(!$res) {
                return ['state'=>0,'errormsg'=>'板块不存在'];
            }
            if($res['moderator_id']){
                if(in_array($this->userId,explode(',',$res['moderator_id']))){
                    return ['state'=>0,'errormsg'=>'您已经是版主'];
                }
                $res['moderator_id'] .= ','.$this->userId;
            }else{
                $res['moderator_id'] = $this->userId;
            }
            $data['moderator_id'] = $res['moderator_id'];
            $res = db('forum_label')->where("label_id = $label_id")->update($data);
            if(!$res){
                return ['state'=>0,'errormsg'=>'失败'];
            }
            return ['state'=>1,'errormsg'=>'成功'];
        }
    }
    //版主列表
    public function moderator_list()
    {
        if(!model('admin')->is('forum')['state']) return ['state'=>0,'errormsg'=>'您没有权限'];
        //查询板块
        $label = db('forum_label')->field('cn,moderator_id,label_id')->where("state = 1")->cache(true,86400)->select();
        foreach ($label as $k =>$v){
            if($v['moderator_id']){
                $user_id = explode(',',$v['moderator_id']);
                foreach ($user_id as $k_k =>$v_v){
                    $user_info = model('user')->getInfoById($v_v);
                    $label[$k]['moderator_name'][$k_k]['user_name'] = isset($user_info['set_name']) ? $user_info['set_name'] : $user_info['user_name'];
                    $label[$k]['moderator_name'][$k_k]['user_id'] = $user_info['user_id'];
                    $label[$k]['moderator_name'][$k_k]['label_id'] = $v['label_id'];
                }

            }
        }
        return ['state'=>1,'data'=>['list'=>$label]];
    }
    //撤销版主
    public function moderator_remove($label_id,$user_id)
    {
        if(!model('admin')->is('forum')['state']) return ['state'=>0,'errormsg'=>'您没有权限'];
        if(!$label_id) return ['state'=>0,'errormsg'=>'请选择板块'];
        if(!$user_id) return ['state'=>0,'errormsg'=>'请选择版主'];
        //查询板块
        $label = \db('forum_label')->where("label_id = $label_id and moderator_id like '%$user_id%'")->cache(true,86400)->find();
        if(!$label) return ['state'=>0,'errormsg'=>'该用户不是版主'];
        //判断该User_id在不在板块里
        $moderator_id = explode(',',$label['moderator_id']);
        foreach ($moderator_id as $k =>$v){
            if($v == $user_id){
                unset($moderator_id[$k]);
            }
        }
        $moderator_id = implode(',',$moderator_id);
        $data['moderator_id'] = $moderator_id;
        $res = \db('forum_label')->where("label_id = $label_id")->update($data);
        if(!$res) return ['state'=>0,'errormsg'=>'撤销版主失败'];
        //信息都有效 执行通知
        $message['value'][$user_id] = "您在 [$label[cn]] 板块的版主职位已被撤销";
        $message['title'] = '系统消息';
        model('message')->send('forum',$message,$user_id);
        return ['state'=>1,'errormsg'=>'撤销版主成功'];
    }

    //--------------------------用户信息------------------------------
    public function getUserInfo($user_id)
    {
        if(!$user_id) return ['state'=>0,'errormsg'=>'参数错误'];
        //查询用户信息
        $userinfo = model('user')->getInfoById($user_id);
        $info['user_name']= isset($userinfo['set_name']) ? $userinfo['set_name'] : $userinfo['user_name'];
        $info['headimgurl']= $userinfo['headimgurl'];
        $info['create_time']= date('Y-m-d H:i:s',$userinfo['join_time']);
        //查询帖子数
        if($this->userId == $user_id) {
            $info['mine'] = true;
            $forum = db('forum')->field('create_time,highlight')->where("user_id = $user_id and state != 0 and state !=4")->order('create_time desc')->cache(true,86400)->select();
        }else{
            $forum = db('forum')->field('create_time,highlight')->where("user_id = $user_id and state = 1 and state !=4")->order('create_time desc')->cache(true,86400)->select();
        }
        $info['user_id'] = $user_id;
        $info['amount'] = count($forum);
        if($forum){
            $info['last_time'] = date('Y-m-d H:i:s',$forum[0]['create_time']);
        }
        $info['highlight'] = 0;
        foreach ($forum as $k =>$v){
            if($v['highlight']){
                $info['highlight'] += 1;
            }
        }
        $empirical_value = db('forum_points')->field('sum(amount) as amount')->where("user_id = $user_id and amount>0")->select()[0]['amount'];
        //判断等级
        if($empirical_value<50){
            $info['empirical_value'] = 'LV1';
        }elseif($empirical_value>=50 && $empirical_value<300){
            $info['empirical_value'] = 'LV2';
        }elseif (($empirical_value>=300 && $empirical_value<500)){
            $info['empirical_value'] = 'LV3';
        }elseif ($empirical_value>=500 && $empirical_value<5000){
            $info['empirical_value'] = 'LV4';
        }elseif ($empirical_value>=5000){
            $info['empirical_value'] = 'LV5';
        }

        return ['state'=>1,'data'=>['info'=>$info]];
    }
    //获取用户帖子列表
    public function getlistbyuserd($user_id,$data,$page = 1)
    {
        if(!$user_id) return ['state'=>0,'errormsg'=>'参数错误'];
        //查询回复
        if($data['reply']) {
            $reply = \db('forum_reply')->alias('r')->join('forum f',"r.forum_id = f.forum_id")
                ->field('r.content,r.create_time,title,r.forum_id,r.user_id')
                ->where("r.user_id = $user_id and r.state = 1 and f.state = 1")
                ->order('create_time desc')->paginate(12, false, ['page' => $page]);
            $pages = $reply->lastPage();
            $reply = $reply->items();
            if (!$reply) return ['state' => 1, 'data' => []];
            $pregRule = "/<img\b[^>]*>/";
            $iframe = "/<iframe\b[^>]*><\\/iframe>/";
            $embed = "/<embed\b[^>]*>/";
            foreach ($reply as $k => $v) {
                if ($v['user_id'] == $this->userId) {
                    $reply[$k]['moved'] = 1;
                }
                $reply[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                preg_match_all($pregRule, htmlspecialchars_decode($v['content']), $im);
                preg_match_all($iframe, htmlspecialchars_decode($v['content']), $if);
                preg_match_all($embed, htmlspecialchars_decode($v['content']), $em);
                if ($im[0]) {
                    $reply[$k]['content'] = str_replace($im[0], '[图片]', htmlspecialchars_decode($v['content']));
                } else if ($if[0]) {
                    $reply[$k]['content'] = str_replace($if[0], '[视频]', htmlspecialchars_decode($v['content']));
                } else if ($em[0]) {
                    $reply[$k]['content'] = str_replace($em[0], '[视频]', htmlspecialchars_decode($v['content']));
                } else {
                    $reply[$k]['content'] = htmlspecialchars_decode($v['content']);
                }
            }
            return ['state'=>1,'data'=>['list'=>$reply],'page'=>$pages];
        }
        if($data['apply']){
            //获取待审核帖子
            $apply = [];
            if($this->userId == $user_id) {
                $apply = db('forum')->field('forum_id,title,label_id,user_id,create_time,reason')->where("state = 3 and user_id = $user_id")->order('create_time')->cache(true,86400)->paginate(12, false, ['page' => $page]);
            }
            if(!$apply) return ['state'=>1,'data'=>[]];
            $pages = $apply->lastPage();
            $apply = $apply->items();
            foreach ($apply as $k =>$v){
                $apply[$k]['create_time'] = date('Y-m-d',$v['create_time']);
            }
            return ['state'=>1,'data'=>['list'=>$apply],'page'=>$pages];
        }
        if($data['fail']){
            //获取审核失败帖子
            $fail = [];
            if($this->userId == $user_id) {
                $fail = db('forum')->field('forum_id,title,label_id,user_id,create_time,reason')->where("state = 4 and user_id = $user_id")->order('create_time')->cache(true,86400)->paginate(12, false, ['page' => $page]);
            }
            if(!$fail) return ['state'=>1,'data'=>[]];
            $pages = $fail->lastPage();
            $fail = $fail->items();
            foreach ($fail as $k =>$v){
                $fail[$k]['create_time'] = date('Y-m-d',$v['create_time']);
            }
            return ['state'=>1,'data'=>['list'=>$fail],'page'=>$pages];
        }
        //查询帖子
        if($this->userId == $user_id){
            $forum = \db('forum')->field('title,label_id,create_time,browse,reply_amount,user_id,forum_id')->where("user_id = $user_id and state !=0 and state !=4")->order('create_time desc')->cache(true,86400)->paginate(12,false,['page'=>$page]);
        }else {
            $forum = \db('forum')->field('title,label_id,create_time,browse,reply_amount,user_id,forum_id')->where("user_id = $user_id and state =1 and state !=4")->order('create_time desc')->cache(true,86400)->paginate(12,false,['page'=>$page]);
        }
        $pages = $forum->lastPage();
        $forum = $forum->items();
        if(!$forum) return ['state'=>1,'data'=>[]];
        $label_name = \db("forum_label")->field("cn,label_id")->cache(true,86400)->select();
        foreach ($forum as $k =>$v){
            if($v['user_id'] == $this->userId){
                $forum[$k]['moved'] = 1;
            }
            foreach ($label_name as $kk =>$vv){
                if($v['label_id'] == $vv['label_id']){
                    $forum[$k]['cn'] = $vv['cn'];
                }
            }
            $forum[$k]['create_time'] = date('Y-m-d',$v['create_time']);
        }

        return ['state'=>1,'data'=>['list'=>$forum,],'page'=>$pages];

    }
    //获取重卡汇表情
    function getexpression()
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        //获取当前用户的等级
        $empirical_value = db('forum_points')->field('sum(amount) as amount')->where("user_id = $this->userId and amount>0")->select()[0]['amount'];
        //判断等级
        if($empirical_value<50){
            $info['empirical_value'] = '1';
        }elseif($empirical_value>=50 && $empirical_value<300){
            $info['empirical_value'] = '2';
        }elseif (($empirical_value>=300 && $empirical_value<500)){
            $info['empirical_value'] = '3';
        }elseif ($empirical_value>=500 && $empirical_value<5000){
            $info['empirical_value'] = '4';
        }elseif ($empirical_value>=5000){
            $info['empirical_value'] = '5';
        }
        $res = db('expression')
            ->field('imgurl')
            ->where("state = 1 and `limit` <= $info[empirical_value]")
            ->order('`range`')
            ->cache(true,86400)
            ->select();
        return ['state' => 1, 'data' => ['list' => $res]];
    }

    //--------------------------数据管理------------------------------
    //统计每天销售额
    public function dataAnalysis($data)
    {
        if ($data['start'] && $data['end']) {
            $startime = strtotime($data['start']);
            $endtime = strtotime($data['end']);
        }
        //时间区间判断
        if (isset($startime) && isset($endtime) && $startime && $endtime) {
            if ($startime == $endtime) {
                $endtime = $startime + 86400;
                $where = "create_time > $startime and create_time < $endtime";
            } else {
                $endtime = $endtime + 86399;
                $where = "create_time > $startime and create_time < $endtime";
            }
            for($i = $startime; $i <= $endtime; $i += 86400)
            {
                $time[date("Y-m-d",$i)]['browse'] = 0;
                $time[date("Y-m-d",$i)]['reply_amount'] = 0;
                $time[date("Y-m-d",$i)]['amount'] = 0;
            }
        }else{
            $startime = strtotime('-1 week')+86400;
            $endtime = strtotime("next Monday")-1;
            for($i = strtotime('-1 week')+86400; $i <= strtotime("next Monday")-1; $i += 86400)
            {
                $time[date("Y-m-d",$i)]['browse'] = 0;
                $time[date("Y-m-d",$i)]['reply_amount'] = 0;
                $time[date("Y-m-d",$i)]['amount'] = 0;
            }
            $where = "create_time > $startime and create_time < $endtime";
        }
        $order = 'create_time';
        //查询发帖量
        $forumlist = \db('forum')->field('create_time')->where($where)->order($order)->cache(true,86400)->select();
        //查询浏览量
        $forumbrowse = \db('forum_browse')->field('create_time')->where($where)->order($order)->cache(true,86400)->select();
        //查询回复量
        $forumreply = \db('forum_reply')->field('create_time')->where($where)->order($order)->cache(true,86400)->select();
        foreach ($forumlist as $k =>$v){
            $list[date('Y-m-d',$v['create_time'])]['count'][] = $v;
        }
        foreach ($forumbrowse as $k =>$v){
            $list[date('Y-m-d',$v['create_time'])]['browse'][] = $v;
        }
        foreach ($forumreply as $k =>$v){
            $list[date('Y-m-d',$v['create_time'])]['reply_amount'][] = $v;
        }
        foreach ($list as $kk =>$vv){
            foreach ($time as $k_k =>$v_v) {
                if ($kk == $k_k) {
                    if(isset($vv['count'])) $time[$kk]['amount'] = count($vv['count']);
                    if(isset($vv['browse'])) $time[$kk]['browse'] = count($vv['browse']);
                    if(isset($vv['reply_amount'])) $time[$kk]['reply_amount'] = count($vv['reply_amount']);
                }
            }
        }
        $temp = [];
        foreach ($time as $k =>$v){
            $temp['browse'][]= $v['browse'];
            $temp['reply_amount'][] = $v['reply_amount'];
            $temp['amount'][] = $v['amount'];
            $temp['day'][] = $k;
        }
        if(!$temp) return ['state'=>0];
        return ['state'=>1,'data'=>['info'=>$temp]];
    }


    public function download($data)
    {
//        header("Content-type:application/vnd.ms-excel;charset:UTF-8");
        $output = fopen('php://output', 'w') or die("can't open php://output");
        header("Content-Type: application/csv;charset:UTF-8");
        $name = "hongyanche_" . "forum";
        if ($data['start'] && $data['end']) {
            $startime = strtotime($data['start']);
            $endtime = strtotime($data['end']);
        }
        //时间区间判断
        if (isset($startime) && isset($endtime) && $startime && $endtime) {
            if ($startime == $endtime) {
                $endtime = $startime + 86400;
                $filename = $name . "_downdload" . " '" . $data['start'] . "' " . date('Y-m-d H:i:s', time());
                $where = "create_time > $startime and create_time < $endtime";
            } else {
                $filename = $name . "_downdload" . " '" . $data['start'] . '--' . $data['end'] . "' " . date('Y-m-d H:i:s', time());
                $endtime = $endtime + 86399;
                $where = "create_time > $startime and create_time < $endtime";
            }
            for($i = $startime; $i <= $endtime; $i += 86400)
            {
                $time[date("Y-m-d",$i)]['browse'] = 0;
                $time[date("Y-m-d",$i)]['reply_amount'] = 0;
                $time[date("Y-m-d",$i)]['amount'] = 0;
            }
        }else{
            $startime = strtotime('-1 week')+86400;
            $endtime = strtotime("next Monday")-1;
            $filename = $name . "_downdload" . " '" . date('Y-m-d',$startime) . '--' . date('Y-m-d',$endtime) . "' " . date('Y-m-d H:i:s', time());
            $where = "create_time > $startime and create_time < $endtime";
        }
        header("Content-Disposition:attachment;filename=" . $filename . ".csv"); //告诉浏览器输出的文件名
//        header('Cache-Control: max-age=0'); //禁止缓存
//        header("Pragma: no-cache");
//        header("Expires: 0");
        //查询发帖信息
        $list = db('forum')->field('forum_id,content,top,highlight,last_reply_time,reason,state',true)->where($where)->where("state = 1")->order('create_time')->select();
        //查询板块名
        foreach ($list as $k =>$v){
            $list[$k]['label_name'] = db('forum_label')->where("label_id = $v[label_id]")->find()['cn'];
            $user_info = model('user')->getInfoById($v['user_id']);
            $list[$k]['user_name'] = isset($user_info['set_name']) ? $user_info['set_name'] : $user_info['user_name'];
            $adminuser_info = model('user')->getInfoById($v['admin_user_id']);
            $list[$k]['admin_user_name'] = isset($adminuser_info['set_name']) ? $adminuser_info['set_name'] : $adminuser_info['user_name'];
        }
        if ($data['code'] == 'utf-8') {
            $create_time = "发帖时间";
            $title = "标题";
            $user_name = "发帖人";
            $fabulous = "点赞量";
            $reply_amount = "评论量";
            $browse_amount = "浏览量";
            $pay = "打赏金额";
            $tag = '标签';
            $admin_user_name = '审核人';
            $label_name = '板块';
        } else {
            $create_time = iconv("UTF-8", "GBK//IGNORE", "发帖时间");
            $title = iconv("UTF-8", "GBK//IGNORE", "标题");
            $user_name = iconv("UTF-8", "GBK//IGNORE", "发帖人");
            $fabulous = iconv("UTF-8", "GBK//IGNORE", "点赞量");
            $reply_amount = iconv("UTF-8", "GBK//IGNORE", "评论量");
            $browse_amount = iconv("UTF-8", "GBK//IGNORE", "浏览量");
            $pay = iconv("UTF-8", "GBK//IGNORE", "打赏金额");
            $tag = iconv("UTF-8", "GBK//IGNORE", "标签");
            $admin_user_name = iconv("UTF-8", "GBK//IGNORE", "审核人");
            $label_name = iconv("UTF-8", "GBK//IGNORE", "板块");

        }
        $table_head = [$create_time,$label_name,$tag,$title,$user_name,$fabulous,$reply_amount,$browse_amount,$pay,$admin_user_name];
        fputcsv($output, $table_head);
        $forumlist = [];
        foreach ($list as $k =>$v){
            if ($data['code'] == 'utf-8') {
                $forumlist[$k][$create_time] = date('Y-m-d H:i:s', $v['create_time']);
                $forumlist[$k][$label_name] = $v['label_name'];
                $forumlist[$k][$tag] = $v['tag'];
                $forumlist[$k][$title] = $v['title'];
                $forumlist[$k][$user_name] = $v['user_name'];
                $forumlist[$k][$fabulous] = $v['fabulous'];
                $forumlist[$k][$reply_amount] = $v['reply_amount'];
                $forumlist[$k][$browse_amount] = $v['browse'];
                $forumlist[$k][$pay] = 0;
                $forumlist[$k][$admin_user_name] = $v['admin_user_name'];
            }else{
                $forumlist[$k][$create_time] = date('Y-m-d H:i:s', $v['create_time']);
                $forumlist[$k][$label_name] = iconv("UTF-8", "GBK//IGNORE", $v['label_name']);
                $forumlist[$k][$tag] = iconv("UTF-8", "GBK//IGNORE", $v['tag']);
                $forumlist[$k][$title] = iconv("UTF-8", "GBK//IGNORE", $v['title']);
                $forumlist[$k][$user_name] = iconv("UTF-8", "GBK//IGNORE", $v['user_name']);
                $forumlist[$k][$fabulous] = $v['fabulous'];
                $forumlist[$k][$reply_amount] = $v['reply_amount'];
                $forumlist[$k][$browse_amount] = $v['browse'];
                $forumlist[$k][$pay] = 0;
                $forumlist[$k][$admin_user_name] = iconv("UTF-8", "GBK//IGNORE", $v['admin_user_name']);
            }
        }
        foreach ($forumlist as $e) {
            fputcsv($output, array_values($e));
        }

        fclose($output) or die("can't close php://output");
        exit;

//        $table = "";
//        $table .= "<table border=1 style='border-collapse: collapse'>
//                            <tr>
//                                <th>" . $create_time . "</th>
//                                <th>" . $label_name . "</th>
//                                <th>" . $tag . "</th>
//                                <th>" . $title . "</th>
//                                <th>" . $user_name . "</th>
//                                <th>" . $fabulous . "</th>
//                                <th>" . $reply_amount . "</th>
//                                <th>" . $pay . "</th>
//                                <th>" . $admin_user_name . "</th>
//                            </tr>";
//        foreach ($list as $k => $v) {
//            $table .="<tr>
//                        <td>".date('Y-m-d H:i:s',$v['create_time'])."</td>
//                        <td>$v[label_name]</td>
//                        <td>$v[tag]</td>
//                        <td>$v[title]</td>
//                        <td>$v[user_name]</td>
//                        <td>$v[fabulous]</td>
//                        <td>$v[reply_amount]</td>
//                        <td>0</td>
//                        <td>$v[admin_user_name]</td>
//                        ";
//        }
//            $table .= "</table>";
//        echo $table;
    }
}